/**
 * Created by csy on 2017/11/20.
 */
var ticketId;
var uploadList = [];
require(['jquery','libs/confirm','easyui','libs/bootstrap3-typeahead','uploadifive'],function($,$confirm){
    //获取url参数
    ticketId = $.getUrlParam("ticketId");
    dataInit(ticketId);
    uploadinit();
    $(document).on("click",'a[name=pass]',function () {
        ajaxRequestMethod({id: $(this).data('id'),status:"P"},"api/v1/p/mms/ticket/checkContent");
    });
    $(document).on("click",'a[name=fail]',function () {
        ajaxRequestMethod({id: $(this).data('id'),status:"F"},"api/v1/p/mms/ticket/checkContent");
    });
    $("input[name='message-check']").on("change",function () {
        if(this.value=='M'){
            ajaxRequestMethod({id: ticketId,status:"M"},"api/v1/p/mms/ticket/updateTicketCheckType");
        }else{
            ajaxRequestMethod({id: ticketId,status:"A"},"api/v1/p/mms/ticket/updateTicketCheckType");
        }
    });
    $("input[name='ticket']").on("change",function () {
        if(this.value=='committed'){
            $confirm("是否打开工单？",function () {
                ajaxRequestMethod({id: ticketId,status:"open"},"api/v1/p/mms/ticket/updateTicket");
            });
        }else{
            $confirm("是否关闭工单？",function () {
                ajaxRequestMethod({id: ticketId,status:"close"},"api/v1/p/mms/ticket/updateTicket");
            });
        }
    });
    $('#userId').typeahead({
        source:function (query, process){
            $.post("api/v1/p/mms/ticket/queryEntInfoAmbiguous",
                {
                    query : query
                },
                function (result) {
                    if(result.code==200){
                        var data = [];
                        if(result.data){
                            $.each(result.data,function (index,obj) {
                                data.push(JSON.stringify(obj));
                            });
                        }
                        process(data);
                    }else{
                        $alert(result.message);
                    }
                });
        },
        items: 9999,
        matcher: function (item) {
            return true;
        },
        highlighter: function (item) {
            var obj = JSON.parse(item);
            return obj.entName+"-"+obj.userName;
        },
        updater: function (item) {
            var obj = JSON.parse(item);
            $('#userId').attr('data-id',obj.userId);
            return obj.entName+"-"+obj.userName;
        }
    });
    $("#user-commit").on("click",function () {
        if($("#userId").val()){
            ajaxRequestMethod({userId:$("#userId").data('id'),userType:"E",tikectId:ticketId},"api/v1/p/mms/ticket/addRelatedUser");
        }
    });
    $('#warehouseId').typeahead({
        source:function (query, process){
            $.post("api/v1/p/mms/ticket/queryWarehouseAmbiguous",
                {
                    query : query
                },
                function (result) {
                    if(result.code==200){
                        var data = [];
                        if(result.data){
                            $.each(result.data,function (index,obj) {
                                data.push(JSON.stringify(obj));
                            });
                        }
                        process(data);
                    }else{
                        $alert(result.message);
                    }
                });
        },
        items: 9999,
        matcher: function (item) {
            return true;
        },
        highlighter: function (item) {
            var obj = JSON.parse(item);
            return obj.warehouseName;
        },
        updater: function (item) {
            var obj = JSON.parse(item);
            $('#warehouseId').attr('data-id',obj.warehouseId);
            return obj.warehouseName;
        }
    });
    $("#warehouse-commit").on("click",function () {
        if($("#warehouseId").val()){
            ajaxRequestMethod({warehouseId:$("#warehouseId").data('id'),userType:"W",tikectId:ticketId},"api/v1/p/mms/ticket/addRelatedUser");
        }
    });
    //发送消息
    $("#commit").on("click",function () {
        if($("#message").val() || $("#uploadList:has(img)").length>0){
            var data = {
                ticketId: ticketId,
                content:$("#message").val()
            };
            data.attachIds = $.map(uploadList,function (o) {
                return {
                    id: o
                }
            });
            ajaxRequestMethod(data,"api/v1/p/mms/ticket/addContent");
            $("#message").val('');
            $("#uploadList").empty();
            uploadList = [];
        }
    });
    $('#uploadList').on('click','.upload-remove',function () {
        var $this = $(this);
        uploadList = $.grep(uploadList, function(value) {
            return value != $this.data('id');
        });
        $(this).parent().remove();
    });
});

function dataInit(ticketId) {
    $.ajax({
        url:'api/v1/p/mms/ticket/load',
        type:'get',
        data:{
            id:ticketId
        },
        dataType:'json'
    })
        .done(function (result) {
            if(result.code == '200'){
                var data = result.data;
                var $firstTarget = $("#basic_info").find("span");
                var $secondTarget = $("#message-list");
                //元素赋值
                if(data.status == "committed" || data.status == 'processed'){
                    //checkType (string, optional): 消息审核(A-on;M-off)
                    $("input[name='message-check'][value='"+data.checkType+"']").attr("checked",true)
                    $("input[name='ticket'][value='"+data.status+"']").attr("checked",true)
                    if(data.userType!='W'){
                        $("#warehouseAdd").show();
                    }
                    if(data.userType!='E'){
                        $("#userAdd").show();
                    }
                }else {
                    $("#console").hide();
                }
                $firstTarget.eq(0).text(data.title);
                $firstTarget.eq(1).text(data.relNo);
                $firstTarget.eq(2).text(data.priority=='2'?'重要':'一般');
                $firstTarget.eq(3).text(data.type);
                $firstTarget.eq(4).text(data.subType);
                $firstTarget.eq(5).text(data.customerName);
                $firstTarget.eq(6).text(data.warehouseName );
                $firstTarget.eq(7).text(data.ticketNo );
                $firstTarget.eq(8).text(data.createDate );
                switch (data.status){
                    case "committed": $firstTarget.eq(9).text("处理中");break;
                    case "processed": $firstTarget.eq(9).text("已处理");break;
                    case "closed": $firstTarget.eq(9).text("已完成");break;
                    default : $firstTarget.eq(9).text("新建");break;
                }
                switch (data.score){
                    case 5: $firstTarget.eq(10).text("非常好");break;
                    case 4: $firstTarget.eq(10).text("好评");break;
                    case 3:  $firstTarget.eq(10).text("一般");break;
                    case 2:  $firstTarget.eq(10).text("差评");break;
                    case 1:  $firstTarget.eq(10).text("非常差");break;
                    default :  $firstTarget.eq(10).text("待评价");break;
                }
                $secondTarget.empty();
                $.each(data.contents,function (index,obj) {
                   //E:企业;W:仓库;M:运营;S:超级管理员
                    var userGroup ,color;
                    var userName=obj.userName;
                    switch (obj.userGroup){
                        case 'E': {userGroup="客户";userName=obj.customerName;color ='orange';break;}
                        case 'W': userGroup="仓库";userName=obj.warehouseName;color ='blue';break;
                        case 'M': userGroup="运营";color ='green';break;
                        case 'S': userGroup="超级管理员";color ='black';break;
                        default: userGroup="";color ='black';
                    }
                    if (obj.createBy==data.userId){
                        userGroup="自己";
                    }
                    //W-待审核、P-审核通过、F-审核不通过
                    var status,fontColor;
                    switch (obj.status){
                        case 'W': status="<a href='javascript:;' name='pass' data-id='"+obj.id+"'>通过</a>|<a href='javascript:;' name='fail' data-id='"+obj.id+"'>不通过</a>";break;
                        case 'P': status="审核通过";fontColor='pass-font';break;
                        case 'F': status="审核不通过";fontColor='red-font';break;
                        default: status="";
                    }
                    var html1 = "<div> <p><span class='sidebaricon' style='color: "+color+";'>&#xe900; </span><font color="+color+">"+userName+"<label>("+userGroup+")：</label>"+obj.content+"</font></p> </div>";
                    var html2 ="<div class='upload-list'></div>";
                    var html3 ="<div class='col-xs-10 bottom-line'><label>"+obj.createDate+"</label></div>"+
                    "<div class='col-xs-2'><label>消息审核：</label><span class='"+fontColor+"'>"+status+"</span> <hr/></div>";

                    var uploadList = $(html2);
                    $.each(obj.attachments,function (i,o) {
                        uploadList.append("<div class='image-wrap'>" +
                        "<i class='glyphicon glyphicon-remove-sign upload-remove' data-id='"+o.id+"'></i>" +
                        "<img src='"+o.filePath+"'></div>");
                    });
                    $secondTarget.append(html1);
                    $secondTarget.append(uploadList);
                    $secondTarget.append(html3);

                });
            }else{
                alert(result.message);
            }
        });
}
function ajaxRequestMethod(data,url,refresh) {
    $.ajax({
        contentType: "application/json; charset=utf-8",
        data:JSON.stringify(data),
        type:"post",
        url:url,
        success:function (result) {
            if(result.code==200){
                if(!refresh) {
                    dataInit(ticketId);
                }
            }else {
                $alert(result.message);
            }
        },
        error:function () {
            console.log(url+" error")
        }
    });
}
function uploadAdd(data) {
    $.each(data,function (i,o) {
        uploadList.push(o.id);
        $('#uploadList').append("<div class='image-wrap'>" +
            "<i class='glyphicon glyphicon-remove-sign upload-remove' data-id='"+o.id+"'></i>" +
            "<img src='"+o.filePath+"'>" +
            "</div>");
    })
}
function uploadinit() {
    $("#uploadifive").uploadifive(
        $.extend({},uploadifiveSettings,{
            uploadScript: 'api/v1/p/crm/fileoper/doUpload',
            fileType: false,
            multi: true,
            fileSizeLimit: '1MB',
            uploadLimit: 2,
            queueSizeLimit: 2,
            onAddQueueItem : function(file) {
                console.log(file.type);
                if(file.type.indexOf('image') > -1){
                    if(uploadList.length > 1){
                        alert('只能上传2个附件');
                        $(this).uploadifive('cancel', file);
                    }
                }else{
                    console.error('不支持'+file.name+'的文件类型。');
                    $(this).uploadifive('cancel', file);
                }
            },
            onSelect: function(){},
            onUploadComplete : function(file, data) {
                var obj = JSON.parse(data);
                if(obj.code == 200){
                    uploadAdd(obj.data);
                }
            },
            onQueueComplete: function(uploads) {
                if(uploads.errors !== 0){
                }
            }
        })
    );
}

